package com.platform.comm.exceptions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MessagesException extends BizException {

    private static final long serialVersionUID = -3597682770835261960L;
    protected List<Map<String, Object>> errors = new ArrayList<>();

    public MessagesException(IErrorCode errorCode, String message) {
        super(errorCode, message);
    }

    public MessagesException(IErrorCode errorCode) {
        super(errorCode);
    }

    public MessagesException(String message) {
        super(message);
    }

    public void pushError(Map<String, Object> error) {
        errors.add(error);
    }

    public void pushMessage(String errorMessage) {
        this.errors.add(buildErrorMessage(errorMessage));
    }

    public boolean hasError() {
        return errors.size() > 0;
    }

    @Override
    public String getMessage() {
        StringBuilder sb = new StringBuilder();
        String message = super.getMessage();
        if (message != null) {
            sb.append(String.format("[%s]", message));
        }
        int count = 1;
        for (Map<String, Object> err : this.errors) {
            String messageItem = getErrorMessage(err).replaceAll("([\r|\n]+)", "\\n");
            sb.append(String.format("%d: %s\n", count++, messageItem));
        }
        return sb.toString();
    }

    protected Map<String, Object> buildErrorMessage(String message) {
        Map<String, Object> error = new HashMap<>();
        error.put("message", message == null ? "" : message);
        return error;
    }

    protected String getErrorMessage(Map<String, Object> error) {
        Object message = error.get("message");
        return message == null ? "" : message.toString();
    }

    @Override
    public String toString() {
        return String.format("%s: %s", getClass().getName(), getMessage());
    }

}
